package com.ideabove.radio.module;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Messenger;
import android.text.Html;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.UnderlineSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.FacebookException;
import com.facebook.FacebookOperationCanceledException;
import com.facebook.HttpMethod;
import com.facebook.Request;
import com.facebook.RequestAsyncTask;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.BaseRequestListener;
import com.facebook.android.Facebook;
import com.facebook.android.Utility;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
import com.facebook.widget.WebDialog;
import com.facebook.widget.WebDialog.OnCompleteListener;
import com.ideabove.data.PlayItem;
import com.ideabove.data.User;
import com.ideabove.network.NetWorkManager;
import com.ideabove.radio.MainActivity;
import com.ideabove.radio.R;
import com.ideabove.radio.module.UserProfileMd.UserRequestListener;
import com.ideabove.radio.service.PlayBackService;
import com.ideabove.radio.service.PlayBackService.MediaPlayerSingleton;
import com.ideabove.util.ConnectThread;
import com.ideabove.util.Connectivity;
import com.ideabove.util.img.ImageLoader;
import com.ideabove.util.kakao.KakaoUtil;

public class FacebookMd{

	public static String PREFERENCE_USER_KEY = "com.ideabove.radio:user";
	public static String PREFERENCE_USER_FB_ID = "com.ideabove.radio:user_fb_id";
	public static String PREFERENCE_USER_FB_FIRST_NM = "com.ideabove.radio:user_fb_first_nm";
	public static String PREFERENCE_USER_FB_LAST_NM = "com.ideabove.radio:user_fb_last_nm";
	public static String PREFERENCE_USER_FB_LAST_EMAIL = "com.ideabove.radio:user_fb_last_email";
	public static String PREFERENCE_USER_FB_PIC_URL = "com.ideabove.radio:user_fb_pic_url";
	public static String PREFERENCE_USER_BONO_ID = "com.ideabove.radio:user_bono_id";
	public static String PREFERENCE_USER_CLUB_NAME = "com.ideabove.radio:user_club_name";

	public static String APP_ID = "330628960346088";
	private boolean isLoginNow = false;

	MainActivity activity 	= null;
	Thread getUserThd = null;
	FacebookCallback fbLoginCallback = null;

	public interface FacebookCallback {
		public void callback();
	}


	RequestCallback rcallback = null;
	public interface RequestCallback {
		public void callback(String msg);
	}


	private UiLifecycleHelper uiHelper;

	private Session.StatusCallback callback = new Session.StatusCallback() {
		@Override
		public void call(Session session, SessionState state, Exception exception) {
			onSessionStateChange(session, state, exception);
		}
	};


	private void onSessionStateChange(Session session, SessionState state, Exception exception) {		
		boolean enableButtons = (session != null && session.isOpened());	
		if(enableButtons && isLoginNow){	

			ModuleAbs.showProgressDialog(activity, "", "잠시만 기다려주세요...");

		}else{
			activity.genreMd.showGenreList();
		}

	}

	public class SampleTestListener extends BaseRequestListener {
		public void onComplete(final String response, final Object state) {   
			Log.i("Facebook-Example","메시지 등록 완료");
		}
	}



	@SuppressLint("HandlerLeak")
	Handler mMainHandler = new Handler() {

		public void handleMessage(Message msg) {
			if("login_completed".equals(msg.obj)){
				hideLoginPage();
				if(rcallback != null){
					rcallback.callback("ok");
					rcallback = null;
				}
			}else if("login_no_main_grene".equals(msg.obj)){	
				hideLoginPage();
				if(rcallback != null){
					rcallback.callback("genreno");
					rcallback = null;
				}				
			}
		}

	};

	public void sendMessage(String msg){
		Message mssg = new Message();
		mssg.obj = msg;
		mMainHandler.sendMessage(mssg);
	}

	public void init(final MainActivity activity){
		this.activity = activity;


		// fb
		LoginButton authButton = (LoginButton) activity.findViewById(R.id.login_button);		
		//		authButton.setFragment(this);		
		//		authButton.setReadPermissions(Arrays.asList("email", "user_status","publish_stream"));
		authButton.setReadPermissions(Arrays.asList("email","user_status"));
		
		authButton.setOnTouchListener(new View.OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				if(event.getAction() == MotionEvent.ACTION_UP){
					CheckBox view = (CheckBox)activity.findViewById(R.id.sign_agree_check);
					if(view.isChecked()){
						v.performClick();
						return false;
					}else{
						
						AlertDialog.Builder ab=new AlertDialog.Builder(activity);  
						ab.setMessage("약관에 동의해 주세요");
						ab.setPositiveButton("ok", null);  
						ab.show();  
						
						return true;
					}
				}
				
				return true;
				
				
			}
		});

		authButton.setUserInfoChangedCallback(new LoginButton.UserInfoChangedCallback() {
			@Override
			public void onUserInfoFetched(GraphUser user) {
				//				Log.e("###U###", "#########" + user);
				if(user != null){
					// fbid setting
					SharedPreferences prefs = activity.getSharedPreferences(FacebookMd.PREFERENCE_USER_KEY, Activity.MODE_PRIVATE ); 
					SharedPreferences.Editor editor = prefs.edit();					
					editor.putString(FacebookMd.PREFERENCE_USER_FB_ID, user.getId());
					editor.putString(FacebookMd.PREFERENCE_USER_FB_FIRST_NM, user.getFirstName()); 
					editor.putString(FacebookMd.PREFERENCE_USER_FB_LAST_NM, user.getLastName());
					editor.putString(FacebookMd.PREFERENCE_USER_FB_LAST_EMAIL, (String)user.getProperty("email"));
					editor.commit();

					ModuleAbs.hideProgressDialog();

					if(fbLoginCallback != null){
						fbLoginCallback.callback();
						fbLoginCallback = null;
						isLoginNow = false;
					}
					// bonosound login
					//					requestGetUserId(user.getId(),user.getFirstName(), user.getLastName());

				}
			}
		});		
	}
	
	private String readText(String file) throws IOException {
		  InputStream is = activity.getAssets().open(file);

		  int size = is.available();
		  byte[] buffer = new byte[size];
		  is.read(buffer);
		  is.close();

		  String text = new String(buffer);

		  return text;
	}

	public void showLoginPage(final FacebookCallback callback){

		AlertDialog.Builder ab = new AlertDialog.Builder(activity);  
		ab.setMessage("로그인 하시겠습니까?");  
		ab.setPositiveButton("ok", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				LinearLayout layout = (LinearLayout)activity.findViewById(R.id.layout_fb_login);
				layout.setVisibility(View.VISIBLE);
				layout.setOnTouchListener(new View.OnTouchListener() {
					
					@Override
					public boolean onTouch(View v, MotionEvent event) {
						// TODO Auto-generated method stub
						return true;
					}
				});
				isLoginNow = true;
			}
		});

		ab.setNegativeButton("cancel", null);
		ab.show();  

		// 밑줄 클릭
		CharSequence sequence = Html.fromHtml("보노사운드의 <u>이용약관 및 개인정보 보호 정책</u> 에 동의합니다");
		SpannableStringBuilder strBuilder = new SpannableStringBuilder(sequence);
		UnderlineSpan[] underlines = strBuilder.getSpans(0,sequence.length(), UnderlineSpan.class);


		for(UnderlineSpan span : underlines) {
			int start = strBuilder.getSpanStart(span);
			int end = strBuilder.getSpanEnd(span);
			int flags = strBuilder.getSpanFlags(span);
			ClickableSpan myActivityLauncher = new ClickableSpan() {
				public void onClick(View view) {

					// 약관 띠우기

					  /* 윈도우 출력 */
					
						
					  LayoutInflater layoutInflater = (LayoutInflater) activity.getBaseContext()
					          .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
					  View popupView = layoutInflater.inflate(R.layout.form_permit, null);
					  TextView textView = (TextView)popupView.findViewById(R.id.term_sign);
					  

					  final PopupWindow popupWindow = new PopupWindow(popupView,
					          LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
					  
					  ImageView close = (ImageView)popupView.findViewById(R.id.window_close);
					  close.setOnClickListener(new View.OnClickListener() {
						
						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							popupWindow.dismiss();
						}
					});
					  
					
					  try {
						  String assetTxt = readText("form_sign.txt");
						  textView.setText(assetTxt);
					  } catch (Exception e) {
						  e.printStackTrace();
					  }
					
						   
						  popupWindow.showAtLocation(popupView, Gravity.CENTER, 0, 0);
//						  popupWindow.showAsDropDown(Popup, 0, (int)Popup.getY()); // 팝업 윈도우를 출력하는 방식
						  // 여기서 버튼의 GetY만큼 띄워준 이유는 페이스북 어플과 같이
						  //버튼 바로 아래에 팝업이 나타나도록 하기 위함입니다.

				}
			};

			strBuilder.setSpan(myActivityLauncher, start, end, flags);
		}

		TextView textView = (TextView)activity.findViewById(R.id.agree_text);
		textView.setText(strBuilder);
		textView.setMovementMethod(LinkMovementMethod.getInstance());

		//		CheckBox chkBox = (CheckBox)
		//		chkBox.setText(Html.fromHtml(activity.getString(R.string.admit)));

		fbLoginCallback = callback;
	}
	public void hideLoginPage(){
		LinearLayout layout = (LinearLayout)activity.findViewById(R.id.layout_fb_login);
		layout.setVisibility(View.GONE);
	}

	public boolean isActiveSession(){
		Session sess = Session.getActiveSession();

		if(sess.isOpened()){
			return true;
		}else{
			return false;
		}
	}

	public String getBonoUserId(){
		SharedPreferences prefs = activity.getSharedPreferences(FacebookMd.PREFERENCE_USER_KEY, Activity.MODE_PRIVATE); 
		String id = prefs.getString(FacebookMd.PREFERENCE_USER_BONO_ID, ""); 
		return id;
	}

	public void requestGetUserId(
			final String fbId, 
			final String fbFirstNm, 
			final String fbLastNm, 
			final String email, 
			final RequestCallback callback)

	{		
		this.rcallback = callback;

		getUserThd = new Thread(new Runnable() {
			public void run(){
				try {	
					//					Log.e("#########requestGetUserId STart", "#####" + fbId);
					HttpClient client = NetWorkManager.getHttpConnection();    
					HttpConnectionParams.setConnectionTimeout(client.getParams(), 1000);					

					HttpPost post = new HttpPost("http://14.63.217.155/radio_bonosound/chkUser.php");
					List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
					params.add(new BasicNameValuePair("fb_id", fbId));
					UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
					post.setEntity(ent);
					HttpResponse responsePOST = client.execute(post);  

					InputStream in = responsePOST.getEntity().getContent();
					BufferedReader reader = new BufferedReader(new InputStreamReader(in));
					StringBuilder str = new StringBuilder();
					String line = null;
					while((line = reader.readLine()) != null)
					{					
						str.append(line);
					}
					in.close();					
					String jsonStr = str.toString();
					//					Log.e("##http://14.63.217.155/radio_bonosound/chkUser.php", "#####" + jsonStr);

					if("0".equals(jsonStr)){ // no sign in user
						addUserNoGenre(fbId, fbFirstNm, fbLastNm, email);												
					}else if("-1".equals(jsonStr)){ // sign in user						
						addUserNoGenre(fbId, fbFirstNm, fbLastNm, email);						
					}else{
						SharedPreferences prefs = activity.getSharedPreferences(FacebookMd.PREFERENCE_USER_KEY, Activity.MODE_PRIVATE ); 
						SharedPreferences.Editor editor = prefs.edit();					
						editor.putString(FacebookMd.PREFERENCE_USER_BONO_ID, jsonStr);
						editor.commit();

						getUserInfo();
						sendMessage("login_completed");
					}



				}catch(Exception e){
					requestGetUserId(fbId, fbFirstNm, fbLastNm, email, callback);
					e.printStackTrace();
				}
				getUserThd = null;	
			}
		});
		getUserThd.start();
	}	

	public void publishFeedDialog(PlayItem playItem) {
		Bundle params = new Bundle();
		//		[OOO님이 보노사운드에서 음악을 공유합니다.]
		//		 유튜브 영상 제목~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
		//		 좋은 음악 네트워크, 보노사운드 - www.bonosound.com

		SharedPreferences prefs = activity.getSharedPreferences(FacebookMd.PREFERENCE_USER_KEY, Activity.MODE_PRIVATE); 
		//		String fbId 		= prefs.getString(FacebookMd.PREFERENCE_USER_FB_ID, "");
		String fbFirstNm 	= prefs.getString(FacebookMd.PREFERENCE_USER_FB_FIRST_NM, "");
		String fbLastNm 	= prefs.getString(FacebookMd.PREFERENCE_USER_FB_LAST_NM, "");

		StringBuffer sbuf = new StringBuffer();
		sbuf.append("[");
		sbuf.append(fbFirstNm);
		sbuf.append(" ");
		sbuf.append(fbLastNm);
		sbuf.append(" 님이 보노사운드에서 음악을 공유합니다.]");

		params.putString("name",  sbuf.toString() );
		params.putString("caption", playItem.getTitle());
		params.putString("description", "www.bonosound.com 좋은 음악 네트워크, 보노사운드 ");
		params.putString("link", "https://www.youtube.com/watch?v=" + playItem.getLink());



		WebDialog feedDialog = (
				new WebDialog.FeedDialogBuilder(activity,
						Session.getActiveSession(),
						params))
						.setOnCompleteListener(new OnCompleteListener() {

							@Override
							public void onComplete(Bundle values, FacebookException error) {
								// TODO Auto-generated method stub
								if (error == null) {
									// When the story is posted, echo the success
									// and the post Id.
									final String postId = values.getString("post_id");
									if (postId != null) {
										Toast.makeText(activity,
												"담벼락에 등록되었습니다",
												Toast.LENGTH_SHORT).show();
									} else {
										// User clicked the Cancel button
										//										Toast.makeText(activity.getApplicationContext(), 
										//												"Publish cancelled", 
										//												Toast.LENGTH_SHORT).show();
									}
								} else if (error instanceof FacebookOperationCanceledException) {
									// User clicked the "x" button
									//									Toast.makeText(activity.getApplicationContext(), 
									//											"Publish cancelled", 
									//											Toast.LENGTH_SHORT).show();
								} else {
									// Generic, ex: network error
									Toast.makeText(activity.getApplicationContext(), 
											"담벼락 등록에 실패하였습니다", 
											Toast.LENGTH_SHORT).show();
								}
							}

						})
						.build();
		feedDialog.show();
	}


	public void addUserNoGenre(final String fbId, 
			final String fbFirstNm, 
			final String fbLastNm, 
			final String email) throws Exception{
		HttpClient client = NetWorkManager.getHttpConnection();
		HttpPost post = new HttpPost("http://14.63.217.155/radio_bonosound/addUser.php");						
		ArrayList <BasicNameValuePair>params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("fbId", fbId));
		params.add(new BasicNameValuePair("fNm", fbFirstNm));
		params.add(new BasicNameValuePair("lNm", fbLastNm));
		params.add(new BasicNameValuePair("email", email));
		UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
		post.setEntity(ent);						
		HttpResponse responsePOST = client.execute(post);  

		InputStream in = responsePOST.getEntity().getContent();
		BufferedReader reader = new BufferedReader(new InputStreamReader(in));
		StringBuilder str = new StringBuilder();
		String line = null;
		while((line = reader.readLine()) != null)
		{					
			str.append(line);
		}
		in.close();					
		String jsonStr = str.toString();
		//		Log.e("#########requestGetUserId jsonStr2", "#####" + jsonStr);

		if(!"0".equals(jsonStr)){
			SharedPreferences prefs = activity.getSharedPreferences(FacebookMd.PREFERENCE_USER_KEY, Activity.MODE_PRIVATE ); 
			SharedPreferences.Editor editor = prefs.edit();					
			editor.putString(FacebookMd.PREFERENCE_USER_BONO_ID, jsonStr);
			editor.commit();

			getUserInfo();
			sendMessage("login_no_main_grene");			
			//			Log.e("#########requestGetUserId jsonStr2", "#####" + prefs.getString(FacebookMd.PREFERENCE_USER_BONO_ID, ""));
		}else{
			// login fail
			Thread.sleep(500);
			throw new Exception();
		}		
	}

	public void getUserInfo() throws Exception{
		HttpClient client = NetWorkManager.getHttpConnection();    
		HttpConnectionParams.setConnectionTimeout(client.getParams(), 1000);					

		HttpPost post = new HttpPost("http://14.63.217.155/radio_bonosound/userInfo.php");
		//		a.	user_id : 유저 ID
		//		b.	fb_id : 페이스북 ID
		//		c.	first_name : 유저이름
		//		d.	last_name : 유저 성
		//		e.	club_name : 클럽이름

		String uId = activity.facebookMd.getBonoUserId();


		if(TextUtils.isEmpty(uId)){
			throw new Exception("parameter error");
		}

		//		Log.e("#########uId", "########" + buserId);
		//		Log.e("#########club_title", "########" + clubName);
		//		Log.e("#########main_genre", "########" + rpGenres.get(0));
		//		Log.e("#########genre_ids", "########" + arrayJoin(",",interGenres));

		ArrayList params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("uId", uId));

		UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
		post.setEntity(ent);

		HttpResponse responsePOST = client.execute(post);  

		InputStream in = responsePOST.getEntity().getContent();
		BufferedReader reader = new BufferedReader(new InputStreamReader(in));
		StringBuilder str = new StringBuilder();
		String line = null;
		while((line = reader.readLine()) != null)
		{					
			str.append(line);
		}
		in.close();					
		String jsonStr = str.toString();

		//		Log.e("#########uId", "getUserInfo########" + jsonStr);

		JSONObject jsonObj = new JSONObject(jsonStr); 
		JSONArray resultArray = jsonObj.getJSONArray("result");

		User user = new User();
		JSONObject jObj = resultArray.getJSONObject(0);
		user.setUser_id(jObj.getString("user_id").toString());
		user.setFb_id(jObj.getString("fb_id").toString());
		user.setFirstName(jObj.getString("first_name").toString());
		user.setLastName(jObj.getString("last_name").toString());
		user.setClub_name(jObj.getString("club_name").toString());

		SharedPreferences prefs = activity.getSharedPreferences(FacebookMd.PREFERENCE_USER_KEY, Activity.MODE_PRIVATE ); 
		SharedPreferences.Editor editor = prefs.edit();	
		editor.putString(FacebookMd.PREFERENCE_USER_FB_ID, user.getFb_id());
		editor.putString(FacebookMd.PREFERENCE_USER_FB_FIRST_NM, user.getFirstName());
		editor.putString(FacebookMd.PREFERENCE_USER_FB_LAST_NM, user.getLastName());
		editor.putString(FacebookMd.PREFERENCE_USER_CLUB_NAME, user.getClub_name());		
		editor.commit();

	}


	public class UserRequestListener extends BaseRequestListener {

		@Override
		public void onComplete(final String response, final Object state) {
			JSONObject jsonObject;
			try {
				jsonObject = new JSONObject(response);

				//				Log.e("###jsonObject##", "#####" + jsonObject.toString());
				final String picURL = jsonObject.getJSONObject("picture")
				.getJSONObject("data").getString("url");
				final String name = jsonObject.getString("name");
				Utility.userUID = jsonObject.getString("id");


				SharedPreferences prefs = activity.getSharedPreferences(FacebookMd.PREFERENCE_USER_KEY, Activity.MODE_PRIVATE ); 
				SharedPreferences.Editor editor = prefs.edit();					
				editor.putString(FacebookMd.PREFERENCE_USER_FB_PIC_URL, picURL);
				editor.commit();

			} catch (JSONException e) {
				e.printStackTrace();
			}
		}

	}

	public void onCreate(Bundle savedInstanceState){
		uiHelper = new UiLifecycleHelper(activity, callback);		
		uiHelper.onCreate(savedInstanceState);

		Utility.mFacebook = new Facebook(APP_ID);
		Utility.mAsyncRunner = new AsyncFacebookRunner(Utility.mFacebook);		

		Bundle params = new Bundle();
		params.putString(Facebook.TOKEN, Session.getActiveSession().getAccessToken());
		params.putString("fields", "name, picture, email");
		Utility.mAsyncRunner.request("me", params, new UserRequestListener());
	}

	public void onResume() {
		uiHelper.onResume();
	}

	public void onPause() {		
		uiHelper.onPause();
	}

	public void onDestroy() {		
		uiHelper.onDestroy();
	}


	public void onSaveInstanceState(Bundle outState) {
		uiHelper.onSaveInstanceState(outState);
	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {		 
		uiHelper.onActivityResult(requestCode, resultCode, data);
	}

	public void onClick(View v,Messenger mMessenger,Messenger mService ){

		if(!Connectivity.isConnected(activity.getApplicationContext())){
			Toast.makeText(activity.getApplicationContext(), "Network is not available.", Toast.LENGTH_SHORT ).show();
			return;
		}

		MediaPlayerSingleton.whatKindOfNetwork = Connectivity.getWhatKindOfNetwork(activity.getApplicationContext());		
		Message msg = Message.obtain(null, PlayBackService.REQUEST_MSG_GET_BONO_CH_PLAYLIST);
		try{
			switch(v.getId()){
			case R.id.radio_every_music:					
				msg.replyTo = mMessenger;
				msg.arg1 = 1; // type
				mService.send(msg);				
				break;

			case R.id.radio_ch_hotsong:
				msg.replyTo = mMessenger;
				msg.arg1 = 2; // type
				mService.send(msg);	
				break;
			case R.id.radio_ch_kpophotsong:
				msg.replyTo = mMessenger;
				msg.arg1 = 3; // type
				mService.send(msg);
				break;
			case R.id.radio_ch_bonoflowfm:
				msg.replyTo = mMessenger;
				msg.arg1 = 4; // type
				mService.send(msg);
				break;

			}		
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	
}
